import logging
import json
import uuid
import os

from . import create_app
from . import db
from . import login_manager
from flask_migrate import Migrate
from concurrent.futures import ThreadPoolExecutor
from flask_apscheduler import APScheduler
from datetime import datetime, timedelta
from flask import render_template, send_from_directory, abort
from flask import jsonify
from flask import request
from .models import User
from flask_login import  login_user

from flask_login import LoginManager, UserMixin, login_user, login_required, logout_user, current_user

app = create_app()

migrate = Migrate(app, db)
login_manager.init_app(app)
login_manager.remember_cookie_duration = timedelta(days=14)
login_manager.remember_cookie_secure = False
login_manager.remember_cookie_httponly = True
login_manager.remember_cookie_name = 'your-remember-me-cookie-name'


# 创建线程池执行器
executor = ThreadPoolExecutor(2)


# 创建定时任务
scheduler = APScheduler()
scheduler.init_app(app)
scheduler.start()


logger = logging.getLogger("app")
logger.setLevel(level=logging.DEBUG)


@app.shell_context_processor
def make_shell_context():
    """
    注册shell命令，可以在shell中执行flask db upgrade命令
    """
    return dict()


# 定时检查任务的执行状态
@scheduler.task('interval', id='check_job_status_task', seconds=10, misfire_grace_time=900)
def check_job_status_task():
    now = datetime.now()
    ts = now.strftime("%Y-%m-%d %H:%M:%S")
    # logger.debug('check_job_status_task executed ' + ts)

    # from .lib.chatops_task import check_jobs_status
    # executor.submit(check_jobs_status, app)


# 允许114的网页镜像跨域调用，获取环境信息列表
@app.after_request
def func_after_request(resp):
    from flask import make_response
    res = make_response(resp)
    res.headers['Access-Control-Allow-Origin'] = '*'
    res.headers['Access-Control-Allow-Methods'] = 'GET,POST'
    res.headers['Access-Control-Allow-Headers'] = 'x-requested-with,content-type'
    return res




@app.route('/hello')
def hello():
    # print('/hello')
    return 'Hello, World!'
    
@app.route('/')
def hello1():
    try:
        #return render_template('index.html') 
        return send_from_directory('static', 'index.html')
    except FileNotFoundError:
        logging.error("File not found: static/index.html")
        abort(404)
    except Exception as e:
        logging.error(f"An unexpected error occurred: {e}", exc_info=True)
        abort(500)    


def allowed_file(filename):
    return '.' in filename and \
           filename.rsplit('.', 1)[1].lower() in app.config["ALLOWED_EXTENSIONS"]

def call_face_detect_2(full_filename):
    import urllib3
    from urllib3.fields import RequestField
    from urllib3.filepost import encode_multipart_formdata  
    
    filename = full_filename.split('/')[-1]
    header = {"Content-Type" : "multipart/form-data"}
    data = {}
    # filename = '文件名'
    # filepath = '文件路径'
    #在data中增加文件key/value
    data['file']= (filename,open(full_filename,'rb').read())
    #转换data数据的类型
    encode_data = encode_multipart_formdata(data)
    data = encode_data[0]
    header['Content-Type'] = encode_data[1]
    
    http = urllib3.PoolManager()
    url = app.config["CORE_API_URL"] + "/detect_face"
    
    res = http.request("POST", url=url, headers=header, body=data)
    print(res.data.decode('utf-8'))
    return json.loads(res.data.decode('utf-8'))
    

@app.route('/upload_file', methods=['GET', 'POST'])
@login_required
def upload_file():
    if request.method == 'POST':
        # check if the post request has the file part
        if 'file' not in request.files:
            return jsonify({'errcode': 10000, 'errmsg': 'No file part'}), 200

        file = request.files['file']
        # If the user does not select a file, the browser submits an
        # empty file without a filename.
        if file.filename == '':
            return jsonify({'errcode': 10000, 'errmsg': 'No selected file'}), 200
        if file and allowed_file(file.filename):
            from werkzeug.utils import secure_filename
            filename = secure_filename(file.filename)
            
            
            random_filename = str(uuid.uuid4())
            # print(random_filename)
            filename = random_filename + "." + filename.split('.')[-1]
            # print(filename)
            
            
            basedir = os.path.abspath(os.path.dirname(__file__))
            filename_url = os.path.join(app.config['UPLOAD_FOLDER'], filename)
            full_filename = os.path.join(basedir, filename_url)
            file.save(full_filename)
            
            res = call_face_detect_2(full_filename)
            res['errcode'] = 0
            res['errmsg'] = f'{filename_url}'
            logger.info(res)
            
            return jsonify(res), 200
    
    return jsonify({'errcode': 0, 'errmsg': ''}), 200


# 存储userid
@login_manager.user_loader
def load_user(user_id):
    return User.query.get(int(user_id))
 
# # 登录视图
# @app.route('/login', methods=['GET'])
# def login():
#     username = request.args.get('username')
#     password = request.args.get('password')
#     user = db.session.query(User).filter(User.username == username).first()
#     if user:
#         #login_user(user)
#         return jsonify({'message': '登录成功', 'user_id': user.id}), 200
#     else:
#         return jsonify({'message': '无效用户名或者密码'}), 401


@login_manager.user_loader
def load_user(user_id):
    # 根据用户ID加载用户
    return User.query.get(int(user_id))

@app.route('/login', methods=['POST'])
def login():

    username = request.form['username']
    password = request.form['password']

    user = db.session.query(User).filter(User.username == username, User.password == password).first()
    logger.debug(user)

    if user is not None:
        login_user(user, remember=True)
        # flask_login.login_user(user)
        return jsonify({'errcode': 0, 'errmsg': '登录成功', 'user_id': user.id, 'username': username}), 200
    else:
        return jsonify({'errcode': 1, 'errmsg': '无效用户名或者密码'}), 401


from flask_login import LoginManager, UserMixin, login_user, login_required, logout_user, current_user
@app.route('/login_status', methods=['GET'])
@login_required
def check_login_status():
    """
    获取成员列表
    """
    print(current_user)
    print(current_user.get_id())
    print(current_user.is_authenticated)

    if current_user.is_authenticated:
        return jsonify({'errcode': 0, 'errmsg': '已登录', 'user_id': current_user.get_id(), 'username': current_user.username}), 200
    else:
        return jsonify({'errcode': 1, 'errmsg': '无效状态'}), 401
    